// 宠物领养
const Router = require("@koa/router");
// 创建 socket

const { pets, petsAdoption, examine, like, ObjectId, chats } = require("../models/mongo");
var jwt = require("jsonwebtoken");

const router = new Router({
    prefix: "/api",
});

// 配置 multer
const path = require('path');
const { writeFile } = require("fs/promises");
const multer = require('@koa/multer');
const upload = multer();

// 自定义中间件
const { verifyToken } = require("../middleware/verity");

// 获取post的body
const { bodyParser } = require("@koa/bodyparser");
const { request } = require("http");

// 领养
// 获取所有帖子
router.get("/pets", async (ctx) => {
    const { isresource = false, page = 1, pageSize = 8, userID = "" } = ctx.query;

    const total = await pets.countDocuments();

    if (userID) {
        const user = jwt.verify(token, "whale")
        let u_id = user.user._id
        let list
        if (isresource) {
            list = await pets
                .find({ u_id, resource: { $ne: "已领养" } })
                .skip((page - 1) * pageSize)
                .limit(pageSize * 1)
                .sort({ _id: -1 })
                .toArray();
        } else {
            list = await pets
                .find({ u_id })
                .skip((page - 1) * pageSize)
                .limit(pageSize * 1)
                .sort({ _id: -1 })
                .toArray();
        }
        const findResAll = await pets.find()
            .toArray();
        ctx.body = {
            code: 200,
            message: "success",
            total,
            page,
            pageSize,
            list,
            findResAll,
        };
    } else {
        let list
        if (isresource) {
            list = await pets
                .find({ resource: { $ne: "已领养" } })
                .skip((page - 1) * pageSize)
                .limit(pageSize * 1)
                .sort({ _id: -1 })
                .toArray();
        } else {
            list = await pets
                .find()
                .skip((page - 1) * pageSize)
                .limit(pageSize * 1)
                .sort({ _id: -1 })
                .toArray();
        }
        const findResAll = await pets.find()
            .toArray();
        ctx.body = {
            code: 200,
            message: "success",
            total,
            page,
            pageSize,
            list,
            findResAll,

        };
    }

    ;
});

// 查询
router.post("/selectpet", bodyParser(), async (ctx) => {
    const { filterQuery, page, pageSize = 8 } = ctx.request.body;
    const total = await pets.countDocuments();
    const list = await pets
        .find(filterQuery)
        .skip((page - 1) * pageSize)
        .limit(pageSize * 1)
        .sort({ _id: -1 })
        .toArray();
    ctx.body = {
        code: 200,
        message: "success",
        total,
        page,
        pageSize,
        list,
    };
});

// 添加 
// 名称、品种、年龄、性格、健康情况、领养地址、发布时间、联系
// name,Variety, age, personality, health, address, time, contact
router.post("/addpet", upload.single("avatar"), async (ctx) => {
    const { name = '', variety = '', age = '', personality = '', health = '', address = '', time = '', contact = '', resource = '送养', token = '', files = [], fileUrl = [], detail = '' } = ctx.request.body;
    const user = jwt.verify(token, "whale")
    // 获取用户id
    let u_id = user.user._id
    const addPetRes = await pets.insertOne({ name, variety, age, personality, health, address, time, contact, resource, u_id, files, fileUrl, detail })

    if (addPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});

// 删除
router.post("/delpet", bodyParser(), async (ctx) => {
    const { id } = ctx.request.body;
    const delPetRes = await pets.deleteOne({ _id: new ObjectId(id) })

    if (delPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});

// 修改
router.post("/updatePet", upload.single("avatar"), async (ctx) => {
    const { id, name = '', variety = '', age = '', personality = '', health = '', address = '', time = '', contact = '', resource = '领养', files = [], fileUrl = [], detail = '' } = ctx.request.body;
    // console.log(ctx);
    let delPetRes
    if (files.length != 0) {
        delPetRes = await pets.updateOne({ _id: new ObjectId(id) }, {
            $set: { name, variety, age, personality, health, address, time, contact, resource, files, fileUrl, detail },
        })
    } else {
        delPetRes = await pets.updateOne({ _id: new ObjectId(id) }, {
            $set: { name, variety, age, personality, health, address, time, contact, resource, detail },
        })
    }

    if (delPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});




// 挂失
// 获取所有帖子
router.get("/petslost", async (ctx) => {
    const { page = 1, pageSize = 8, token = "" } = ctx.query;
    const total = await petsAdoption.countDocuments();

    if (token != "") {
        try {
            const user = jwt.verify(token, "whale")
            let u_id = user.user._id
            const list = await petsAdoption
                .find({ u_id })
                .skip((page - 1) * pageSize)
                .limit(pageSize * 1)
                .sort({ _id: -1 })
                .toArray();
            const findResAll = await petsAdoption.find()
                .toArray();
            ctx.body = {
                code: 200,
                message: "success",
                total,
                page,
                pageSize,
                list,
                findResAll
            };
        } catch (error) {
            ctx.body = {
                code: 400,
                message: "error",
            };
        }

    } else {
        const list = await petsAdoption
            .find()
            .skip((page - 1) * pageSize)
            .limit(pageSize * 1)
            .sort({ _id: -1 })
            .toArray();
        const findResAll = await petsAdoption.find()
            .toArray();
        ctx.body = {
            code: 200,
            message: "success",
            total,
            page,
            pageSize,
            list,
            findResAll
        };
    }
});

// 查询
router.post("/selectpetlost", bodyParser(), async (ctx) => {
    const { filterQuery, page, pageSize = 8 } = ctx.request.body;
    const total = await petsAdoption.countDocuments();
    const list = await petsAdoption
        .find(filterQuery)
        .skip((page - 1) * pageSize)
        .limit(pageSize * 1)
        .sort({ _id: -1 })
        .toArray();
    ctx.body = {
        code: 200,
        message: "success",
        total,
        page,
        pageSize,
        list,
    };
});

// 添加
// 名称、品种、年龄、性格、健康情况、领养地址、发布时间、联系
// name,Variety, age, personality, health, address, time, contact
router.post("/addpetlost", bodyParser(), async (ctx) => {
    // console.log(ctx.request.body);

    const { name = '', address = '', time = '', contact = '', token = '', files = [], detail = '', price = '' } = ctx.request.body;

    const user = jwt.verify(token, "whale")
    let u_id = user.user._id
    const addPetRes = await petsAdoption.insertOne({ name, address, time, contact, u_id, files, resource: '挂失', detail, price })
    if (addPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});
// 删除
router.post("/delpetlost", bodyParser(), async (ctx) => {
    const { id } = ctx.request.body;
    const delPetRes = await petsAdoption.deleteOne({ _id: new ObjectId(id) })

    if (delPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});

// 修改
router.post("/updatePetlost", upload.single("avatar"), async (ctx) => {
    const { id, name = '', variety = '', age = '', personality = '', health = '', address = '', time = '', contact = '', files = [], detail = '', price = '' } = ctx.request.body;
    let delPetRes

    if (files.length != 0) {
        delPetRes = await petsAdoption.updateOne({ _id: new ObjectId(id) }, {
            $set: { name, variety, age, personality, health, address, time, contact, files, detail, price },
        })
    } else {
        delPetRes = await petsAdoption.updateOne({ _id: new ObjectId(id) }, {
            $set: { name, variety, age, personality, health, address, time, contact, detail, price },
        })
    }

    if (delPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});


// 审批
// 查询
router.get("/examine", async (ctx) => {
    const { id, page = 1, pageSize = 8 } = ctx.query;

    const total = await examine.countDocuments();
    const infoCount = await examine.countDocuments({ status: "待审批" })
    if (id) {
        const list = await examine.aggregate([
            {
                $match: { userID: new ObjectId(id) } // 使用 $match 来过滤文档
            },
            {
                $lookup: {
                    from: "users", // 要连接的集合名称
                    localField: "userID", // 当前集合中用于连接的字段
                    foreignField: "_id", // 被连接集合中用于连接的字段
                    as: "users" // 输出的字段名称，将连接后的用户信息存储在这个字段中
                }
            },
            {
                $lookup: {
                    from: "pets", // 要连接的集合名称
                    localField: "petID", // 当前集合中用于连接的字段
                    foreignField: "_id", // 被连接集合中用于连接的字段
                    as: "pets" // 输出的字段名称，将连接后的用户信息存储在这个字段中
                }
            },
        ])
            .sort({ _id: -1 })

            .toArray();
        ctx.body = {
            code: 200,
            message: "success",
            list,
            infoCount
        };
    } else {
        const list = await examine.aggregate([
            {
                $lookup: {
                    from: "users", // 要连接的集合名称
                    localField: "userID", // 当前集合中用于连接的字段
                    foreignField: "_id", // 被连接集合中用于连接的字段
                    as: "users" // 输出的字段名称，将连接后的用户信息存储在这个字段中
                }
            },
            {
                $lookup: {
                    from: "pets", // 要连接的集合名称
                    localField: "petID", // 当前集合中用于连接的字段
                    foreignField: "_id", // 被连接集合中用于连接的字段
                    as: "pets" // 输出的字段名称，将连接后的用户信息存储在这个字段中
                }
            },
        ])
            .sort({ _id: -1 })
            .skip((page - 1) * pageSize)
            .limit(pageSize * 1)
            .toArray();
        ctx.body = {
            code: 200,
            message: "success",
            total,
            page,
            pageSize,
            list,
            infoCount
        };
    }
});
// 申请列表
router.get("/petexamine", async (ctx) => {
    const { petid, page = 1, pageSize = 8 } = ctx.query;

    const total = await examine.countDocuments();

    const list = await examine.aggregate([
        {
            $match: { petID: new ObjectId(petid) } // 使用 $match 来过滤文档
        },
        {
            $lookup: {
                from: "users", // 要连接的集合名称
                localField: "userID", // 当前集合中用于连接的字段
                foreignField: "_id", // 被连接集合中用于连接的字段
                as: "users" // 输出的字段名称，将连接后的用户信息存储在这个字段中
            }
        },
        {
            $lookup: {
                from: "pets", // 要连接的集合名称
                localField: "petID", // 当前集合中用于连接的字段
                foreignField: "_id", // 被连接集合中用于连接的字段
                as: "pets" // 输出的字段名称，将连接后的用户信息存储在这个字段中
            }
        },
    ])
        .skip((page - 1) * pageSize)
        .limit(pageSize * 1)
        .sort({ _id: -1 })
        .toArray();
    ctx.body = {
        code: 200,
        message: "success",
        list,
        total
    };
});
// 收藏列表
router.get("/like", async (ctx) => {
    const { userID, page = 1, pageSize = 8 } = ctx.query;

    const total = await like.countDocuments();

    const list = await like.aggregate([
        {
            $match: { userID: new ObjectId(userID) } // 使用 $match 来过滤文档
        },
        {
            $lookup: {
                from: "pets", // 要连接的集合名称
                localField: "petID", // 当前集合中用于连接的字段
                foreignField: "_id", // 被连接集合中用于连接的字段
                as: "pets" // 输出的字段名称，将连接后的用户信息存储在这个字段中
            }
        },
    ])
        .skip((page - 1) * pageSize)
        .limit(pageSize * 1)
        .sort({ _id: -1 })
        .toArray();
    ctx.body = {
        code: 200,
        message: "success",
        list,
        total
    };
});
// 添加
router.post("/addexamine", bodyParser(), async (ctx) => {
    const { userID, petID, petName } = ctx.request.body;
    const time = new Date().toLocaleString()

    const addRes = await examine.insertOne({ userID: new ObjectId(userID), petID: new ObjectId(petID), petName, time, status: "待审批" })
    if (addRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});
// 添加收藏
router.post("/addlike", bodyParser(), async (ctx) => {
    const { userID, petID } = ctx.request.body;
    const time = new Date().toLocaleString()

    const addRes = await like.insertOne({ userID: new ObjectId(userID), petID: new ObjectId(petID), time, })
    if (addRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});

// 修改
router.post("/updateexamine", bodyParser(), async (ctx) => {
    const { _id, userID, petID, petName, time, status } = ctx.request.body;

    examineRes = await examine.updateOne({ _id: new ObjectId(_id) }, {
        $set: { userID: new ObjectId(userID), petID: new ObjectId(petID), petName, time, status },
    })

    if (examineRes) {
        switch (status) {
            case "通过审核":
                examineRes = await pets.updateOne({ _id: new ObjectId(petID) }, {
                    $set: { resource: '已领养' },
                })
                examineRes = await examine.updateOne({ _id: { "$ne": new ObjectId(_id) }, petID: new ObjectId(petID) }, {
                    $set: { status: '宠物已被领养' },
                })
                break
            default:
                break
        }
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});
//删除
router.post("/delexamine", bodyParser(), async (ctx) => {
    const { id } = ctx.request.body;
    const delPetRes = await examine.deleteOne({ _id: new ObjectId(id) })

    if (delPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});
// 删除收藏
router.post("/dellike", bodyParser(), async (ctx) => {
    const { petID, userID } = ctx.request.body;

    const delPetRes = await like.deleteOne({ petID: new ObjectId(petID), userID: new ObjectId(userID) })

    if (delPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});


// 图片
router.post("/upload-cover", upload.fields([
    {
        name: 'file',
        maxCount: 6
    }
]), async (ctx) => {
    const avatarName = ctx.request.files?.file[0]?.originalname;
    console.log("post /upload-img", avatarName);

    await writeFile(path.resolve(__dirname, "../uploads/", avatarName), ctx.request.files?.file[0]?.buffer);
    ctx.body = {
        message: '添加成功'
    };
});



//聊天室
// 查询房间聊天记录
router.get("/chats", async (ctx) => {
    const { roomId } = ctx.query;

    const list = await chats
        .find({ roomId })
        .toArray();
    ctx.body = {
        code: 200,
        message: "success",
        list,
    };
});
// 创建房间
router.post("/addchats", bodyParser(), async (ctx) => {
    const { roomId, chatsList = [] } = ctx.request.body
    console.log(roomId, chatsList);
    const list = await chats.find({ roomId }).toArray()

    if (list.length == 0) {
        const addRes = await chats.insertOne({ roomId, chatsList })
        if (addRes) {
            ctx.body = {
                code: 200,
                message: "添加成功",
            };
        }
    } else {
        ctx.body = {
            message: "已有房间"
        }
    }

});
// 添加信息
router.post("/updatechats", bodyParser(), async (ctx) => {
    const { roomId, chatsList } = ctx.request.body;
    const addRes = await chats.updateOne({ roomId }, {
        $set: { roomId, chatsList },
    })

    if (addRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});
// 用户聊天列表
router.post("/allchat", bodyParser(), async (ctx) => {
    const { userId } = ctx.request.body
    const list = await chats
        .find({ roomId: userId })
        .toArray();
    ctx.body = {
        code: 200,
        message: "success",
        list,
    };
});
// 聊天列表
router.get("/allchat", async (ctx) => {
    const list = await chats
        .find()
        .toArray();
    ctx.body = {
        code: 200,
        message: "success",
        list,
    };
});


module.exports = router;
